package ren.nearby.http.exception;

import android.content.Context;
import android.content.Intent;
import android.widget.Toast;


import com.orhanobut.logger.Logger;

import java.util.HashMap;
import java.util.Map;

import es.dmoral.toasty.Toasty;
import ren.nearby.http.exception.RetrofitException;
import ren.nearby.http.meepo.Meepo;
import ren.nearby.http.meepo.config.UriConfig;
import ren.nearby.http.request.ActivityRouter;
import ren.nearby.http.utils.util.PreferencesUtils;

/**
 * 描述：网络统一异常处理
 */
public class NetworkError {
    static ActivityRouter router;

    static {
        final Meepo meepo = new Meepo.Builder()
                .config(new UriConfig().scheme("action").host("nearby.action"))
                .build();
        router = meepo.create(ActivityRouter.class);
    }

    /**
     * @param context 可以用于跳转Activity等操作
     */
    public static void error(Context context, Throwable throwable) {
        RetrofitException.ResponeThrowable responeThrowable = RetrofitException.retrofitException(throwable);
        Logger.e("code = " + responeThrowable.code + " - " + responeThrowable.message);
        // 此处可以通过判断错误代码来实现根据不同的错误代码做出相应的反应
        switch (responeThrowable.code) {
            case RetrofitException.ERROR.NOT_LOGIN:
                Toasty.error(context, responeThrowable.message).show();
                PreferencesUtils.putBoolean(context, "login_", false);
                PreferencesUtils.putInt(context, "user_id", -1);
                // 跳转到登陆页面
                Map<String, String> map = new HashMap<String, String>();
                map.put("value1", "值1");
                map.put("value2", "值2");
                //多个参数传递与跳转Code与返回
                map.put("value3", "值3");
                router.toHomeLogin(context, map);
                break;
            case RetrofitException.ERROR.UNKNOWN:
            case RetrofitException.ERROR.PARSE_ERROR:
            case RetrofitException.ERROR.NETWORD_ERROR:
            case RetrofitException.ERROR.HTTP_ERROR:
            case RetrofitException.ERROR.SSL_ERROR:
                Toasty.error(context, responeThrowable.message).show();
                break;
            default:
                Toasty.error(context, responeThrowable.message).show();
                break;
        }
    }
}
